package com.boss.controller;

import com.alibaba.fastjson2.JSON;
import com.boss.service.WebRTCSessionService;
import com.boss.service.WebSocketSessionService;
import com.boss.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import static com.boss.service.WebRTCSessionService.SESSION_POOL;


@Component
@Slf4j
public class WebRTCHandler extends AbstractWebSocketHandler {
    Integer num = 1;
    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        // 在收到消息后，将消息广播给所有连接到服务器的客户端
        String messageStr = message.getPayload().toString();
        System.out.println(session.getRemoteAddress() + " 发送消息：" + messageStr);
        System.out.println("json:" + JSON.parseObject(message.getPayload().toString()));
        if (SESSION_POOL.size() < 2) {
            System.out.println("对方不在线");
            UserVo userVo = new UserVo();
            userVo.setType("-1");
            userVo.setMsg("对方不在线");
            System.out.println(JSON.toJSONString(userVo));
            SESSION_POOL.get(session.getId()).sendMessage(new TextMessage(JSON.toJSONString(userVo)));
        } else {
            try {
//            String status = (String) JSON.parseObject(message.getPayload().toString()).get("status");
                System.out.println(JSON.parseObject(message.getPayload().toString()));
                System.out.println("消息次数:" + num);
                num += 1;
                for (Map.Entry<String, WebSocketSession> entry : SESSION_POOL.entrySet()) {
                    if (!entry.getValue().getId().equals(session.getId())) {
                        entry.getValue().sendMessage(new TextMessage(JSON.toJSONString(JSON.parseObject(message.getPayload().toString()))));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        log.info(session.getId() + "建立WebRTC连接");
        System.out.println(session);
        WebRTCSessionService.add(session.getId(), session);
        session.sendMessage(new TextMessage(session.getId() + "建立WebRTCSessionServiceWebRTC连接！"));
    }


    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        log.error("异常处理");
        WebRTCSessionService.removeAndClose(session.getId());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        log.info("关闭ws连接");
        WebRTCSessionService.removeAndClose(session.getId());
    }
}